# @Time : 2024-09-29 11:27
# @Author : Fioman 
# @Phone : 13149920693
"""
上料相机拼接工具
"""
import cv2 as cv
import gevent
import numpy as np

import app_config
from common.data_result import DataResult
from common.file_dir_helper import open_dir
from common.produce_logger import ProduceLogger
from db_tools.db_handler import DbHandler
from tools.line_camera_params import LineCameraParams

db = DbHandler()
cp = LineCameraParams()
logger = ProduceLogger()


class ImageJointTool(object):
    def __init__(self, left_cam, mid_cam, right_cam, cam_zmc):
        self.left_cam = left_cam
        self.mid_cam = mid_cam
        self.right_cam = right_cam
        self.cam_zmc = cam_zmc
        self.left_img = None
        self.mid_img = None
        self.right_img = None
        self.reload_image_joint_params()

    def reload_image_joint_params(self):
        """
        图像拼接参数加载,就是图像截取的位置,这些参数来控制图像的拼接
        :return:
        """
        result = db.get_image_jont_params()
        if result.state:
            params = result.data
            self.left_cam_start_offset = params.get("left_cam_start_offset")
            self.left_cam_end_offset = params.get("left_cam_end_offset")
            self.mid_cam_start_offset = params.get("mid_cam_start_offset")
            self.mid_cam_end_offset = params.get("mid_cam_end_offset")
            self.right_cam_start_offset = params.get("right_cam_start_offset")
            self.right_cam_end_offset = params.get("right_cam_end_offset")
            self.left_cam_height_offset = params.get("left_cam_height_offset")
            self.right_cam_height_offset = params.get("right_cam_height_offset")
        else:
            logger.debug(result.info)

    @staticmethod
    def web_request_open_image_joint_dir():
        """
        打开某个目录
        :return:
        """
        result = open_dir(app_config.image_joint_dir)
        if not result.state:
            logger.debug(result.info)
            return result.info
        return "ok"

    def get_image_from_line_cam(self):
        """
        从线阵相机那里获取图片
        @return:
        """
        result = DataResult()
        self.left_cam.clear_buffer()
        self.mid_cam.clear_buffer()
        self.right_cam.clear_buffer()
        res = self.cam_zmc.set_allow_take_pic()
        self.cam_zmc.clear_img_result_failed()
        if not res.state:
            result = res
            return result
        res_left = self.left_cam.get_image_line()
        if not res_left.state:
            result = res_left
            return result
        res_middle = self.mid_cam.get_image_line()
        if not res_middle.state:
            result = res_middle
            return result
        res_right = self.right_cam.get_image_line()
        if not res_right.state:
            result = res_right
            return result
        self.left_img, self.mid_img, self.right_img = res_left.data, res_middle.data, res_right.data
        joint_image = self.get_joint_image()
        result.data = joint_image
        return result

    def get_joint_image(self):
        """
        根据拼接参数,获取拼接图像
        @return:
        """
        left_image = self.left_img[:self.left_cam_start_offset:(self.left_img.shape[1] -
                                                                self.left_cam_end_offset)]
        middle_image = self.mid_img[:self.mid_cam_start_offset:(self.mid_img.shape[1] -
                                                                self.mid_cam_end_offset)]
        right_image = self.right_img[:self.right_cam_start_offset:(self.right_img.shape[1] -
                                                                   self.right_cam_end_offset)]
        new_left_image = np.zeros(left_image.shape, dtype=np.uint8)
        if self.left_cam_height_offset < 0:  # 向上移动
            new_left_image[:(left_image.shape[0] - abs(self.left_cam_height_offset))] = left_image[
                                                                                        abs(self.left_cam_height_offset):]
        elif self.left_cam_height_offset > 0:  # 向下移动
            new_left_image[self.left_cam_height_offset:] = left_image[
                                                           :(left_image.shape[1] - abs(self.left_cam_height_offset))]
        else:
            new_left_image = left_image

        new_right_image = np.zeros(right_image.shape, dtype=np.uint8)
        if self.right_cam_height_offset < 0:  # 向上移动
            new_right_image[:(right_image.shape[0] - abs(self.right_cam_height_offset))] = left_image[
                                                                                           abs(self.right_cam_height_offset):]
        elif self.right_cam_height_offset > 0:  # 向下移动
            new_right_image[self.right_cam_height_offset:] = right_image[
                                                             :(right_image.shape[1] - abs(self.right_cam_height_offset))]
        else:
            new_right_image = right_image

        joint_image = np.hstack((new_left_image, middle_image, new_right_image))
        h, w = joint_image.shape[:2]
        joint_image = cv.resize(joint_image, (w, int(h * cp.height_wid_ratio)))
        joint_image = cv.flip(joint_image, 1)  # 左右镜像反转
        return joint_image

    def re_start_line_camera(self):
        """
        重新打开线阵相机
        @return:
        """
        self.left_cam.stop_grabbing()
        self.mid_cam.stop_grabbing()
        self.right_cam.stop_grabbing()
        gevent.sleep(1)
        self.left_cam.start_grabbing()
        self.mid_cam.start_grabbing()
        self.right_cam.start_grabbing()


if __name__ == '__main__':
    image_joint = ImageJointTool(None, None, None, None)
    image_joint.web_request_open_image_joint_dir()
